/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.nhncorp.neptune.changelog.previous;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.neptune.common.conf.NConfiguration;
import com.nhncorp.neptune.common.io.NWritableUtils;
import com.nhncorp.neptune.common.util.FileUtil;
import com.nhncorp.neptune.fs.ChangeLogFileSystemIF;
import com.nhncorp.neptune.tabletserver.ChangeLog;

public class FileChangeLogManager {
  public static final Log LOG = LogFactory.getLog(FileChangeLogManager.class.getName());
  
  //파일명이 중요하다. 반드시 CHANGE_LOG_FILE_NAME가 CHANGE_LOG_OLD_FILE_NAME보다 사전적으로 뒤에 오도록 명명
  public static final String CHANGE_LOG_FILE_NAME = "change_z.log";

  public static final String CHANGE_LOG_OLD_FILE_NAME = "change_a.log.";

  private DataOutputStream out;
  
  private ReadFileInfo readFileInfo; 
  
  private String logFilePath;

  private Object monitor = new Object();
  
  private String hostName;
  
  public FileChangeLogManager(NConfiguration conf, String tabletName, String hostName) {
    this.logFilePath = conf.get("changelog.data.dir") + "/" + tabletName;
    this.hostName = hostName;
  }
  
  public String addChangeLog(String txId, int seq, ChangeLog changeLog) {
    readFileInfo = null;
    /*
     * 처리 도중 장애 발생 시 return 값에는 Exception 메세지를 전달한다.
     * 장애가 발생하면 해당 Tablet에 대한 log 파일을 더 이상 관리하지 않는다.
     */
    try {
      synchronized(monitor) {
        if(out == null) {
          File file = new File(logFilePath);
          file.mkdirs();
          out = new DataOutputStream(new FileOutputStream(logFilePath + "/" + CHANGE_LOG_FILE_NAME, true));
        } 
        int writeLen = NWritableUtils.writeString(out, txId);
        out.writeInt(seq);
        changeLog.write(out);
        
        //마지막 레코드 정보를 읽어 오기 위해 레코드의 마지막에 길이 저장
        long size =  writeLen +                                     //txId 
                      NWritableUtils.getIntByteSize() +               //seq
                      changeLog.getByteSize() +                      //change log
                      NWritableUtils.getLongByteSize();               //writeByte length
        
//        System.out.printf("%d %d %d %d %d\n", writeLen, WritableUtils.getIntByteSize(), 
//            changeLog.getByteSize(), WritableUtils.getLongByteSize(), size);
        out.writeLong(size);
        
        out.flush();
        return ChangeLogFileSystemIF.ADD_OK;
      }
    } catch (Exception e) {
      LOG.error("Error while add change log[" + e.getMessage() + "]. delete change log file", e);
      try {
        delete();
      } catch(Exception err) {
        LOG.error("change log delete error", err);
      }
      return e.getMessage();
    }
  }

  public void close(boolean writable) {
    if(writable) {
      if(out != null) {
        try {
          out.close();
          out = null;
        } catch (Exception err) {
          LOG.error("change log out.close error", err);
        }
      }
    } else {
      if(readFileInfo != null) {
        DataInputStream in = readFileInfo.din;
        if(in != null) {
          try {
            in.close();
          } catch (Exception err) {
            LOG.error("change log in.close error", err);
          }
        }
        readFileInfo = null;
      }
    }
  }
  
  public void close() {
    close(true);
    close(false);
  }
  
  public void delete() throws IOException {
    close();
    
    File file = new File(logFilePath);
    if(!file.exists()) {
      LOG.warn("No log file:" + logFilePath);
    } else {
      FileUtil.delete(logFilePath, true);
    }
  }
  
  public ChangeLogStatus getChangeLogStatus() throws IOException {
    File file = new File(logFilePath);
    if(!file.exists()) {
      return new ChangeLogStatus();
    }
    ChangeLogStatus changeLogStatus = new ChangeLogStatus();
    File[] files = file.listFiles();
    if(files == null || files.length == 0) {
      return changeLogStatus;
    }
    
    long totalFileSize = 0;
    for(File eachFile: files) {
      if(eachFile.isFile()) {
        if(eachFile.length() == 0) {
          eachFile.delete();
        } else {
          totalFileSize += eachFile.length();
        }
      }
    }
    
    if(totalFileSize == 0) {
      file.delete();
      LOG.info("Changelog file delete:" + file + " cause file length is zero");
      return changeLogStatus;
    }
    
    long fileSize = 0;
    String maxTxId = "";
    int maxSeq = 0;
    
    for(File eachFile: files) {
      try {
        if(eachFile.length() == 0) {
          LOG.info("Change log file length is zero. so skip file:" + eachFile);
          continue;
        }
        
        fileSize += eachFile.length();
        RandomAccessFile in = new RandomAccessFile(eachFile, "r");
        long seekPos = eachFile.length() - NWritableUtils.getLongByteSize();
        
        if( seekPos < 0) {
          LOG.error("Can't get last change log record:" + eachFile + ",filelen=" + eachFile.length());
          continue;
        }
        in.seek(seekPos);
        long lastRecordSize = in.readLong();
        //System.out.println(">>>>" + lastRecordSize + ">" + (eachFile.length() - lastRecordSize));
        in.seek(eachFile.length() - lastRecordSize);
  
        String txId = NWritableUtils.readString(in);
        int seq = in.readInt();
        
        in.close();
        
        if(txId.compareTo(maxTxId) > 0) {
          maxTxId = txId;
        }
        
        if(seq > maxSeq) {
          maxSeq = seq;
        }
      } catch (IOException e) {
        LOG.error("Error while ChangeLogSuatus from " + hostName, e);
        throw e;
      }
    }
    
    changeLogStatus.setMaxTxId(maxTxId);
    changeLogStatus.setMaxSeq(maxSeq);
    changeLogStatus.setFileCount(files.length);
    changeLogStatus.setFileSize(fileSize);
    changeLogStatus.setHostName(hostName);
    
    return changeLogStatus;
  }

  /**
   * ChangeLog 파일로 부터 ChangeLog 레코드를 읽는다.
   * @param tabletName
   * @return
   * @throws IOException
   */
  public ChangeLog nextChangeLog() throws IOException {
    close(true);
    DataInputStream in = null;
    try {
      if(readFileInfo == null) {
        File file = getNextFile();
        if(file == null) {
          return null;
        }
        readFileInfo = new ReadFileInfo();
        in = new DataInputStream(new FileInputStream(file));
        readFileInfo.fileName = file.getName();
        readFileInfo.din = in;
      } else {
        in = readFileInfo.din;
      }
      return readChangeLog(in);
    } catch(EOFException e) {
      if(in != null) {
        in.close();
      }
      //다음번 파일에서 레코드를 읽을 수 있는 파일이 있을때까지 
      while(true) {
        File file = getNextFile();
        if(file == null) {
          readFileInfo = null;
          return null;
        }
        in = new DataInputStream(new FileInputStream(file));
        readFileInfo.fileName = file.getName();
        readFileInfo.din = in;
        
        try {
          return readChangeLog(in);
        } catch(EOFException err) {
        }
      }
    }
  }

  private File getNextFile() {
    if(readFileInfo == null) {
      File file = new File(logFilePath);
      String[] files = file.list();
      if(files == null || files.length == 0) {
        return null;
      } else {
        return new File(file, files[0]);
      } 
    } else {
      File file = new File(logFilePath);
      String[] files = file.list();
      if(files == null || files.length == 0 || files.length == 1) {
        return null;
      }
      
      Arrays.sort(files, 0, files.length);
      for(int i = 0; i < files.length; i++) {
        if(readFileInfo.fileName.equals(files[i]) && i < (files.length - 1)) {
          return new File(file, files[i + 1]);
        }
      }
      
      return null;
    }
  }
  
  private ChangeLog readChangeLog(DataInputStream in) throws IOException {
    String txId = NWritableUtils.readString(in);
    int seq = in.readInt();
    
    ChangeLog changeLog = new ChangeLog();
    changeLog.readFields(in);
    
    long size = in.readLong();
    
    return changeLog;
  }

  public boolean rollingLogFile(String tabletName) {
    try {
      synchronized(monitor) {
        if(out != null) {
          //기존에 저장되는 파일은 close 시키고 old로 rename 한다.
          out.close();
          out = null;
        }
        File originFile = new File(logFilePath + "/" + CHANGE_LOG_FILE_NAME);
        if(originFile.exists()) {
          long timestamp = System.currentTimeMillis();
          File newFile = new File(logFilePath + "/" + CHANGE_LOG_OLD_FILE_NAME + timestamp);
          if(!originFile.renameTo(newFile)) {
            LOG.error("Can't rename " + originFile + " to " + newFile.getName());
            return false;
          }
        }
        
        //새로운 파일을 생성한다.
        File file = new File(logFilePath);
        file.mkdirs();
        
        out = new DataOutputStream(new FileOutputStream(logFilePath + "/" + CHANGE_LOG_FILE_NAME, true));
        
        return true;
      }
    } catch (Exception e) {
      LOG.error(e);
      return false;
    }
  }
  
  public boolean deleteOldFile() {
    try {
      File file = new File(logFilePath);
      File[] files = file.listFiles();
      if(files == null && files.length == 0) {
        return false;
      }
      //LOG.debug("deleteOldFile:" + logFilePath + ":" + files.length);
      for(File eachFile: files) {
        if(CHANGE_LOG_FILE_NAME.equals(eachFile.getName())) {
          continue;
        } else {
          //LOG.info("Delete old log file:" + eachFile + ",size=" + eachFile.length());
          boolean result = eachFile.delete();
          if(!result) {
            LOG.error("Can't delete old log file:" + eachFile);
            return false;
          }
        }
      }
      return true;
    } catch (Exception e) {
      LOG.error(e);
      return false;
    }
  }
  
  static class ReadFileInfo {
    String fileName;
    DataInputStream din;
  }
}
